﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace 晨曦超市管理系统
{
    class DBHelper
    {
        public static string sqlstr = "Data Source=LL6KTUXIVJS796B;Initial Catalog=ChenXi;Integrated Security=True";

        public static SqlConnection connection = null;
        //判断数据库的状态。
        public static void Inconnention()
        {
            if (connection == null)
                connection = new SqlConnection(sqlstr);
            if (connection.State == ConnectionState.Broken)
            {
                connection.Close();
                connection.Open();
            }
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
        }

        //意思就是这样慢慢理解

        //后面循环的一次只返回一行所以用whin（a.Reader()）；
        public static SqlDataReader DateReader(string sqlstr) {
            Inconnention();
            SqlCommand cmd = new SqlCommand(sqlstr, connection);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);       //一定要用完就关掉
        }

        //填充da.Table.Row[][];我自己做例子有的
        //在哪个数据表格就不要这样直接da.Table.ToString();
        public static DataTable GetDataTable(string sqlstr) {
            Inconnention();
            DataTable Table = new DataTable();
            SqlDataAdapter Adapter = new SqlDataAdapter(sqlstr,connection);
            Adapter.Fill(Table);
            connection.Close();       //一定要用完就关掉
            return Table;
        }

        //看我的返回值对不，大于0就是有效。
        public static bool QEX(string sqlstr) {
            Inconnention();
            SqlCommand Command = new SqlCommand(sqlstr,connection);
            int a = Command.ExecuteNonQuery();
            connection.Close();      //一定要用完就关掉
            return a > 0;
        }

        //聚合函数的返回值
        public static object JuHeHanShu(string sqlstr) {
            Inconnention();
            SqlCommand Command = new SqlCommand(sqlstr,connection);
            object a=Command.ExecuteScalar();
            connection.Close();     //一定要用完就关掉
            return a;
        }
    }
}
